<template>
  <div>
    <!-- 编辑界面保存的信息 -->
    <div class="app-container">
      <el-row :gutter="20">
        <el-col :span="24" class="my-plan-title-box">
          <div class="my-info-title">需求单队列查询</div>
          <div>
            <el-button v-waves @click="getList">
              查询
            </el-button>
            <el-button @click="handleReset">
              重置
            </el-button>
            <el-button @click="handleExport">
              导出
            </el-button>
          </div>
        </el-col>
      </el-row>
      <div class="filter-container">
        <el-form ref="filterFrom" :model="listQuery" :inline="true" class="demo-form-inline" label-width="5rem">
          <el-form-item prop="reqNo" label="需求单号">
            <el-input v-model="listQuery.reqNo" style="width: 12rem;" clearable/>
          </el-form-item>
          <el-form-item prop="reportFactoryCode" label="提报工厂">
            <OrgFactoryCode style="width: 12rem;" :params="{ valuable: '1' }"
                            v-model="listQuery.reportFactoryCode" :is-form-data="true" keyName="werksD"/>
          </el-form-item>
          <el-form-item prop="appUnitCode" label="申请单位">
            <WorkUnit v-model="listQuery.appUnitCode" style="width: 12rem;" placeholder=" "/>
          </el-form-item>
          <el-form-item prop="reqCustNo" label="需求客户">
            <CustomerInfo v-model="obj.reqCustNo" keyName="code" keyShow="code" title="客户查询"
                          style="width: 12rem;" :is-form-data="true"/>
          </el-form-item>
          <el-form-item prop="salesOrg" label="销售组织">
            <SaleCode v-model="listQuery.salesOrg" style="width: 12rem" placeholder=" "/>
          </el-form-item>
          <el-form-item prop="materialCode" label="物料">
            <MaterialCode size="small" v-model="listQuery.materialCode" keyName="code" :is-form-data="true"
                          style="width: 12rem" placeholder=" " title="物料查询"/>
          </el-form-item>
          <el-form-item prop="planDodStart" class="wraplabel" label="计划交货日期开始">
            <el-date-picker v-model="listQuery.planDodStart" type="datetime" style="width: 12rem;"
                            value-format="YYYY-MM-DD HH:mm:ss"/>
          </el-form-item>
          <el-form-item prop="planDodEnd" class="wraplabel" label="计划交货日期结束">
            <el-date-picker v-model="listQuery.planDodEnd" type="datetime" style="width: 12rem;"
                            value-format="YYYY-MM-DD HH:mm:ss"/>
          </el-form-item>
          <el-form-item prop="createBy" label="创建人">
            <User v-model="listQuery.createBy" keyName="account" keyShow="userName" placeholder=" "
                  style="width: 12rem" title="用户查询"/>
          </el-form-item>
          <el-form-item prop="applicant" label="需求者">
            <el-input v-model="listQuery.applicant" style="width: 12rem;" clearable/>
          </el-form-item>
          <el-form-item prop="createTimeStart" class="wraplabel" label="创建日期开始">
            <el-date-picker v-model="listQuery.createTimeStart" type="datetime" style="width: 12rem;"
                            value-format="YYYY-MM-DD HH:mm:ss"/>
          </el-form-item>
          <el-form-item prop="createTimeEnd" class="wraplabel" label="创建日期结束">
            <el-date-picker v-model="listQuery.createTimeEnd" type="datetime" style="width: 12rem;"
                            value-format="YYYY-MM-DD HH:mm:ss"/>
          </el-form-item>
        </el-form>
      </div>
      <el-row :gutter="20">
        <el-col :span="24" class="my-plan-title-box">
          <div class="my-info-title">列表详情</div>
          <div style="display: flex;">
            <el-button @click="handleSure">保存</el-button>
            <el-button :disabled="!multipleSelection.length" @click="handleDelete">移除</el-button>
            <InventorySales :disabled="multipleSelection.length !== 1" :params="InventorySalesParams"
                            style="margin-left: 10px;margin-right: 10px;"/>
            <QueryInventory :params="queryInventoryParams" @getStockList="getStockList"/>
            <HistoricalDemandList :disabled="multipleSelection.length !== 1"
                                  :params="historicalDemandListParams" style="margin-left: 10px;"/>
          </div>
        </el-col>
      </el-row>

      <el-table border :data="tableData" @selection-change="handleSelectionChange" :row-style="rowStyle">
        <el-table-column show-overflow-tooltip type="selection" fixed="left"></el-table-column>
        <el-table-column show-overflow-tooltip label="序号">
          <template v-slot="{ row, column, $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="需求单号" prop="reqNo" min-width="100"></el-table-column>
        <el-table-column show-overflow-tooltip label="行项目号" prop="reqItemNo">
          <template v-slot="scope">
            <a style="color:blue;">{{ scope.row.reqItemNo }}</a>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="退货标识" prop="rogFlag">
          <template v-slot="{ row }">
            <DictTag :dict-list="rog_flag" :dict-key="row.rogFlag" />
          </template>
        </el-table-column>
        <el-table-column label="受托业务" prop="commissionBusiCode" min-width="180px">
          <template #header>
            <span style="color:red;">*</span><span>受托业务</span>
          </template>
          <template v-slot="{ row }">
            <el-select disabled v-model="row.commissionBusiCode">
              <el-option v-for="item in commission_busi" :key="item.value" :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
            <!-- <el-select :disabled="!row.taskName.includes('产品经理') || row.reqTypeCode==='YT' || row.reportFactoryCode !== row.purFactory" v-model="row.commissionBusiCode" :class="row.notVerifyArr && row.notVerifyArr.includes('commissionBusiCode') ? 'is-error' : ''">
                <el-option v-for="item in commission_busi" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
            <span v-if="row.notVerifyArr && row.notVerifyArr.includes('commissionBusiCode')" class="errorTip">请填写</span> -->
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="免费标识" prop="freeFlag" min-width="120px">
          <template v-slot="{ row }">
            <el-select :disabled="!row.taskName.includes('产品经理') || row.reqTypeCode === 'YT'"
                       v-model="row.freeFlag">
              <el-option v-for="item in free_flag" :key="item.value" :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="提报数量" prop="submitQuantity"></el-table-column>
        <el-table-column label="可用库存" prop="availableStock" min-width="105px">
          <template v-slot="{ row }">{{ row.availableStock }}</template>
        </el-table-column>
        <el-table-column label="审核数量" prop="approveNum" min-width="180px">
          <template #header>
            <span style="color:red;">*</span><span>审核数量</span>
          </template>
          <template v-slot="{ row }">
            <el-input-number :disabled="!row.taskName.includes('产品经理') || row.reqTypeCode === 'YT'"
                             v-model="row.approveNum"
                             :class="row.notVerifyArr && row.notVerifyArr.includes('approveNum') ? 'is-error' : ''"></el-input-number>
            <span v-if="row.notVerifyArr && row.notVerifyArr.includes('approveNum')"
                  class="errorTip">请填写</span>
          </template>
        </el-table-column>
        <el-table-column label="供货方式" prop="supplyMode" min-width="180px">
          <template #header>
            <span style="color:red;">*</span><span>供货方式</span>
          </template>
          <template v-slot="{ row }">
            <el-select :disabled="!row.taskName.includes('产品经理') || row.reqTypeCode === 'YT'"
                       v-model="row.supplyMode"
                       :class="row.notVerifyArr && row.notVerifyArr.includes('supplyMode') ? 'is-error' : ''">
              <!-- <el-option v-for="item in row.supplyModeOptions" :key="item.key" :label="item.label"
                         :value="item.value"></el-option> -->
              <el-option
                  v-if="row.rogFlag === '1' || row.reqTypeCode === 'NB' || row.reqTypeCode === 'Z1'|| row.reqTypeCode === 'Z2' || row.reqTypeCode === 'Z4' || row.reqTypeCode === 'UB' || row.reqTypeCode === 'Z5' "
                  label="调拨" value="X"/>
              <el-option
                  v-if="row.reqTypeCode === 'NB' || row.reqTypeCode === 'Z1' || row.reqTypeCode === 'Z2' || row.reqTypeCode === 'Z4' || row.reqTypeCode === 'A0' || row.reqTypeCode === 'A1' || row.reqTypeCode === 'CB' "
                  label="对外采购" value="W"/>
              <el-option v-if="row.reqTypeCode === 'CB'" label="仅销售" value="Y"/>
            </el-select>
            <span v-if="row.notVerifyArr && row.notVerifyArr.includes('supplyMode')"
                  class="errorTip">请填写</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="采购工厂" prop="purFactory"></el-table-column>
        <el-table-column show-overflow-tooltip label="采购库存地点" prop="purInventoryAdd" min-width="130px">
          <template v-slot="{ row }">
            <LocationCode :disabled="!row.taskName.includes('产品经理') || row.reqTypeCode === 'YT'"
                          v-model="row.purInventoryAdd"
                          :params="{ werksD: row.purFactory }" keyName="lgortD" placeholder=""
                          @onchange="(selectRow, list) => { LocationCodeOnChange(selectRow, list, row) }"
                          title="库存查询">
            </LocationCode>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="计划交货日期" prop="planDod" min-width="170px">
          <template #header>
            <span style="color:red;">*</span><span>计划交货日期</span>
          </template>
          <template v-slot="{ row }">
            <el-date-picker :disabled="!row.taskName.includes('产品经理') || row.reqTypeCode === 'YT'"
                            style="width:100%;"
                            :disabled-date="disabledDate" value-format="YYYY-MM-DD HH:mm:ss" type="date"
                            :class="row.notVerifyArr && row.notVerifyArr.includes('planDod') ? 'is-error' : ''"
                            v-model="row.planDod"></el-date-picker>
            <span v-if="row.notVerifyArr && row.notVerifyArr.includes('planDod')"
                  class="errorTip">请填写</span>
          </template>
        </el-table-column>
        <el-table-column label="指定供应商" prop="designatedSupplier" min-width="180px">
          <template v-slot="{ row }">
            <Supplier :disabled="!row.taskName.includes('产品经理') || row.reqTypeCode === 'YT'"
                      v-model="row.designatedSupplier"
                      keyName="lifnr" placeholder="" title="供应商查询"
                      :class="row.notVerifyArr && row.notVerifyArr.includes('designatedSupplier') ? 'is-error' : ''"
                      @onchange="(selectRow, list) => { designatedSupplierOnChange(selectRow, list, row) }">
            </Supplier>
            <span v-if="row.notVerifyArr && row.notVerifyArr.includes('designatedSupplier')"
                  class="errorTip">请填写</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="供应商名称" prop="designatedSupplierName"
                         min-width="120px;"></el-table-column>
        <el-table-column show-overflow-tooltip label="平均周转周数" prop="averageTurnover"
                         min-width="120px;"></el-table-column>
        <!-- <el-table-column show-overflow-tooltip label="是否预付物料" prop="prepaidFlag" min-width="120px;"/> -->
        <el-table-column label="预估提货后总仓周转率" prop="whseTurnoverRate" min-width="120px">
          <template v-slot="{ row }">
            <el-input :disabled="!row.taskName.includes('产品经理') || row.reqTypeCode === 'YT'"
                      placeholder=""
                      v-model="row.whseTurnoverRate"
                      :class="row.notVerifyArr && row.notVerifyArr.includes('whseTurnoverRate') ? 'is-error' : ''"></el-input>
            <span v-if="row.notVerifyArr && row.notVerifyArr.includes('whseTurnoverRate')"
                  class="errorTip">请填写</span>
          </template>
        </el-table-column>
        <el-table-column label="预估提货后全公司周转率" prop="coTurnoverRate" min-width="120px">
          <template v-slot="{ row }">
            <el-input :disabled="!row.taskName.includes('产品经理') || row.reqTypeCode === 'YT'"
                      placeholder=""
                      v-model="row.coTurnoverRate"
                      :class="row.notVerifyArr && row.notVerifyArr.includes('coTurnoverRate') ? 'is-error' : ''"></el-input>
            <span v-if="row.notVerifyArr && row.notVerifyArr.includes('coTurnoverRate')"
                  class="errorTip">请填写</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="特殊说明" prop="specialDesc" min-width="180px">
          <template v-slot="{ row }">
            <el-input :disabled="!row.taskName.includes('产品经理') || row.reqTypeCode === 'YT'"
                      v-model="row.specialDesc"></el-input>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="物料编码" prop="materialCode"
                         min-width="150px"></el-table-column>
        <el-table-column show-overflow-tooltip label="物料描述" prop="materialDesc"
                         min-width="100px"></el-table-column>
        <el-table-column show-overflow-tooltip label="计量单位" prop="uomCode"></el-table-column>
        <!-- <el-table-column show-overflow-tooltip label="计量单位文本" prop="uomText" min-width="120px"></el-table-column>
        <el-table-column show-overflow-tooltip label="审批状态" prop="approvalStatus">
            <template v-slot="{row}">
                <DictTag :dict-list="sale_exec_price_status" :dict-key="row.approvalStatus" />
            </template>
        </el-table-column> -->
        <el-table-column show-overflow-tooltip label="需求者" prop="applicant"></el-table-column>
        <el-table-column show-overflow-tooltip label="提报工厂" prop="reportFactoryCode"
                         min-width="100px"></el-table-column>
        <el-table-column show-overflow-tooltip label="申请单位" prop="appUnitName"></el-table-column>
        <el-table-column show-overflow-tooltip label="到货库存地点" prop="arrivalInventoryAdd"
                         min-width="110px;"></el-table-column>
        <el-table-column show-overflow-tooltip label="销售组织" prop="salesOrgName"></el-table-column>
        <el-table-column show-overflow-tooltip label="销售办事处" prop="salesOfficeName"
                         min-width="100px;"></el-table-column>
        <el-table-column show-overflow-tooltip label="需求客户" prop="reqCustName"></el-table-column>
        <el-table-column show-overflow-tooltip label="送货地址编码" prop="deliveryAddNo"
                         min-width="120px"></el-table-column>
        <el-table-column show-overflow-tooltip label="送货地址" prop="deliveryAddDesc"
                         min-width="100px"></el-table-column>
        <!-- <el-table-column show-overflow-tooltip label="提报单价" prop="reportPrice"></el-table-column> -->
        <!-- <el-table-column show-overflow-tooltip label="提报金额" prop="reportAmount"></el-table-column> -->
        <el-table-column show-overflow-tooltip label="采购组" prop="purGroupCode"></el-table-column>
        <el-table-column show-overflow-tooltip label="采购组描述" prop="purGroupDesc"
                         min-width="100px;"></el-table-column>
        <el-table-column show-overflow-tooltip label="物料组" prop="materialGroupCode"
                         min-width="100px"></el-table-column>
        <el-table-column label="物料组描述" prop="materialGroupDesc" min-width="100px"
                         show-overflow-tooltip></el-table-column>
        <el-table-column show-overflow-tooltip label="品牌代码" prop="brandCode"
                         min-width="100px"></el-table-column>
        <el-table-column label="品牌描述" prop="brandDesc" min-width="100px"
                         show-overflow-tooltip></el-table-column>
        <el-table-column show-overflow-tooltip label="原单号" prop="originReqNo"></el-table-column>
        <el-table-column show-overflow-tooltip label="原单行项目号" prop="originReqItemNo"></el-table-column>
        <el-table-column show-overflow-tooltip label="退货产品串码号" prop="rogImeiCode"></el-table-column>
        <el-table-column show-overflow-tooltip label="参考提报价格" prop="refOfferPrice"></el-table-column>
        <el-table-column show-overflow-tooltip label="省分采购价格（含税）" prop="provincePurPrice"
                         min-width="120px"></el-table-column>
        <el-table-column show-overflow-tooltip label="备注" prop="remarks"></el-table-column>
        <el-table-column show-overflow-tooltip label="创建时间" prop="createTime"
                         min-width="120px"></el-table-column>
        <el-table-column show-overflow-tooltip label="创建人" prop="createBy" min-width="120px">
          <template v-slot="{ row }">
            {{ userObj[row.createBy] }}
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="需求类型" prop="reqTypeCode" min-width="145px">
          <template v-slot="{ row }">
            <DictTag :dict-list="req_type" :dict-key="row.reqTypeCode" />
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="需求单明细状态" prop="reqItemStatus">
          <template v-slot="{ row }">
            <DictTag :dict-list="req_status" :dict-key="row.reqItemStatus" />
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="客户号" prop="reqCustNo"></el-table-column>
        <el-table-column show-overflow-tooltip label="专题会公文号" prop="topicDocNo"></el-table-column>
        <!-- <el-table-column show-overflow-tooltip label="创建时间" prop="createTime" min-width="120px"></el-table-column> -->
        <!-- <el-table-column show-overflow-tooltip label="创建人" prop="createBy" min-width="120px">
        </el-table-column> -->
        <el-table-column align="center" label="操作" width="160px" fixed="right">
          <template v-slot="{ row }">
            <el-button link @click="handleView(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 审批信息 -->
    <div class="app-container">
      <el-row>
        <el-col :span="24">
          <el-form class="my-form" label-width="7rem" label-position="right">
            <el-row>
              <el-col :span="24">
                <el-form-item label="审批意见" prop="comment">
                  <el-input type="textarea" v-model="obj.comment" placeholder=""/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
      <div style="text-align:right;">
        <el-button @click="complete('Y')">同意</el-button>
        <el-button @click="complete('N')">驳回</el-button>
        <el-button @click="doClose">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {doGet, doPost, doPut, doDelete, doDownload, getUsers, doPostDownload} from '@/config/http'
import InventorySales from '@/components/approve/InventorySales'
import QueryInventory from '@/components/approve/QueryInventory'
import HistoricalDemandList from '@/components/approve/HistoricalDemandList'
import LocationCode from '@/components/share/LocationCode'
import MaterialCode from '@/components/share/MaterialCode/'
import SaleCode from "@/components/share/SaleCode";
import Supplier from '@/components/share/Supplier'
import {supplyModeOptionsMap} from '@/components/approve/supplyModeOptionsMap'
import OrgFactoryCode from "@/components/share/OrgFactoryCode";
import WorkUnit from "@/components/share/WorkUnit";
import CustomerInfo from "@/components/share/CustomerInfo";
import User from "@/views/components/bpm/user.vue";
import useTodoStore from "@/store/modules/bpm/todo";
import useUserStore from '@/store/modules/user'
import {getPathByName} from "@/router";
import {notifySuccess} from "@/config/common";

export default {
  // 内置监听器相关信息
  data() {
    const dictObj = this.useDict('req_type', 'rog_flag', 'commission_busi', 'free_flag', 'supply_mode', 'sale_exec_price_status', 'req_status')
    return {
      listQuery: {
        reqNo: null,
        reportFactoryCode: null,
        appUnitCode: null,
        reqCustNo: null,
        salesOrg: null,
        materialCode: null,
        planDodStart: null,
        planDodEnd: null,
        createBy: null,
        applicant: null,
        createTimeStart: null,
        createTimeEnd: null,
      },
      multipleSelection: [],
      disabledDate: function (time) {
        return time.getTime() < Date.now - 86400000
      },
      tableData: [],
      obj: {
        comment: '', // 审批意见
      },
      ...dictObj,
      userObj: {},
      listParams: {},

    }
  },
  created() {
    this.getList()
  },
  computed: {
    historicalDemandListParams() {
      let params = null
      if (this.multipleSelection.length > 0) {
        params = this.multipleSelection.map(item => {
          return {
            appUnitCode: item.appUnitCode, // 申请单位
            materialCode: item.materialCode, // 物料编码
            purFactory: item.purFactory, // 采购工厂
            purGroupCode: item.purGroupCode, // 采购组编码
            purInventoryAdd: item.purInventoryAdd, // 采购库存地点
            reportFactoryCode: item.reportFactoryCode // 提报工厂
          }
        })[0]
      }
      return params
    },
    InventorySalesParams() {
      let params = null
      if (this.multipleSelection.length > 0) {
        params = this.multipleSelection.map(item => {
          return {
            materialCode: item.materialCode, // 物料编码
            factory: item.reportFactoryCode, // 提报工厂
            inventoryAdd: item.arrivalInventoryAdd, // 到货库存地点
            approveNum: item.submitQuantity //提报数量
          }
        })[0]
      }
      return params
    },
    queryInventoryParams() {
      return this.multipleSelection.map(item => {
        return {
          materialCode: item.materialCode, // 物料编码
          purFactory: item.reportFactoryCode, // 提报工厂
          purInventoryAdd: item.arrivalInventoryAdd, // 采购库存地点
          availableStockRuleCode: 'A'
        }
      })
    },
  },
  components: {
    CustomerInfo,
    WorkUnit,
    OrgFactoryCode,
    InventorySales,
    QueryInventory,
    HistoricalDemandList,
    LocationCode,
    Supplier,
    MaterialCode,
    SaleCode,
    User
  },
  methods: {
    //查询库存回显
    getStockList(stockList) {
      const {tableData, multipleSelection} = this
      multipleSelection.forEach(item => {
        let {reqNo, reqItemNo, materialCode, purFactory, purInventoryAdd} = item
        if (!materialCode) {
          materialCode = null
        }
        if (!purFactory) {
          purFactory = null
        }
        if (!purInventoryAdd) {
          purInventoryAdd = null
        }
        const listItem = tableData.find(i => i.reqNo == reqNo && i.reqItemNo == reqItemNo)// 通过单据号与单据行项目号匹配
        const stockItem = stockList.find(i => i.materialCode == materialCode && i.factoryCode == purFactory && i.inventoryAdd == purInventoryAdd) // 通过物料编码，采购工厂，采购库存地点匹配
        console.log({listItem, stockItem})
        listItem.availableStock = stockItem?.availableInventoryNum
      })
    },
    rowStyle({row, rowIndex}) {
      let styleJson = {
        "background-color": "rgb(209, 240, 230)",
        "height": "70px"
      };
      if (row.error) {
        return styleJson
      } else {
        return {}
      }
    },
    handleSure() {
      let arr = JSON.parse(this.$route.query.params)
      let approvalItemVoList = this.tableData.map(item => {
        let obj = {
          // procInsId: item.procInsId,	// 流程实例ID
          procInsId: arr.find(item1 => (item.reqNo + item.reqItemNo) === item1.businessKey).procInsId,	// 流程实例ID
          // taskId: item.taskId,	// 任务唯一标识
          taskId: arr.find(item1 => (item.reqNo + item.reqItemNo) === item1.businessKey).taskId,	// 任务唯一标识
          reqItemExVo: {
            ...item
          }
        }
        return obj
      })
      console.log(approvalItemVoList)
      doPost('peas-module-plan-biz', '/req/batch-modify', approvalItemVoList).then(res => {
        console.log('res', res)
        notifySuccess('操作成功')
        this.getList()
      })
    },

    handleDelete() {
      this.$confirm('确定要移除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.listDelete()
      })
    },
    listDelete() {
      let queryParams = JSON.parse(this.$route.query.params)
      let deleteItemArr = []
      this.multipleSelection.forEach((item) => {
        deleteItemArr.push(item.reqNo + item.reqItemNo)
        let index = this.tableData.indexOf(item)
        this.tableData.splice(index, 1)
      })
      this.multipleSelection = []
      let newQueryParams = queryParams.filter(item => !deleteItemArr.includes(item.businessKey))
      if (newQueryParams.length) {
        let params = JSON.stringify(newQueryParams)
        console.log({params})
        this.$router.replace({query: {params}})
      } else {
        this.doClose()
      }
    },
    handleExport() {
      doPostDownload('peas-module-plan-biz', `/req/export/approve-req-list`, this.listParams)
    },
    handleReset() {
      this.$refs.filterFrom.resetFields()
      this.getList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getUrlByReqTypeCode(reqTypeCode) {
      // 一般直运政企："NB", "集团内一般需求单"、"Z1", "直运需求单"、"Z4", "政企统一供货平台需求单"
      // 苹果新品： "A0", "苹果FAST SHIP需求单"、"A1", "苹果FAST SHIP正式需求单"
      // 内部购销： "UB", "内部购销需求单")
      // 内部调拨： "Z5", "调拨需求单"
      // 客户：   "CB", "客户一般需求单"
      // 一键通退货： "YT", "苹果一键通退货需求单"
      let pathUrl = ''
      let editUrl = ''
      switch (reqTypeCode) {
        case 'NB':
        case 'Z1':
        case 'Z4':
          pathUrl = 'CommonlyDropShipmentEnterpriseHidden'//'/plan/group-requirements/view-hidden'
          editUrl = 'PlanGroupRequirementsEdit'//'/plan/group-requirements/edit'
          break
        case 'A0':
        case 'A1':
          pathUrl = 'newAppleProductsHidden'//'/plan/group-requirements/new-apple-products-hidden'
          editUrl = 'newAppleProductsEdit'//'/plan/group-requirements/new-apple-products-edit'
          break
        case 'UB':
          pathUrl = 'InternalPurchaseAndSalesHidden'//'/plan/group-requirements/internal-purchase-sales-view-hidden'
          editUrl = 'InternalPurchaseAndSalesEdit'//'/plan/group-requirements/internal-purchase-sales-edit'
          break
        case 'Z5':
          pathUrl = 'InternalTransferHidden'//'/plan/group-requirements/internal-transfer-view-hidden'
          editUrl = 'InternalTransferEdit'//'/plan/group-requirements/internal-transfer-edit'
          break
        case 'CB':
          pathUrl = 'BigCustomerRequestFormHidden' //'/plan/customer-request-form/big-view-hidden'
          editUrl = 'BigCustomerRequestFormEdit' //'/plan/customer-request-form/big-edit'
          break
        case 'YT':
          pathUrl = 'OneClickReturnHidden'//'/plan/customer-request-form/one-click-return-hidden'
          editUrl = 'OneClickReturnEdit' //'/plan/customer-request-form/one-click-return-edit'
          break
      }
      return {
        pathUrl,
        editUrl
      }
    },
    handleView(row) {
      let {editUrl} = this.getUrlByReqTypeCode(row.reqTypeCode)
      let path = getPathByName(editUrl)
      path = path.replace(':id?', row.reqNo + row.reqItemNo)
      let from = 'batchApproval'
      this.$tab.openPage({
        path,
        query: {id: row.id, dialogType: 'view', from, params: this.$route.query.params}
      })
    },
    getSupplyModeOptions(item) {
      let billTypeCode = 'PLAN-' + item.reqTypeCode
      if (item.rogFlag === '1') {
        billTypeCode = 'TUIHUO'
      }
      console.log({billTypeCode}, this.supply_mode)
      let supplyModeOptionsMapRes = supplyModeOptionsMap.get(billTypeCode)
      if (!item.supplyMode) {
        item.supplyMode = supplyModeOptionsMapRes.default
      }
      let options = this.supply_mode.filter(item => {
        return supplyModeOptionsMapRes.options.indexOf(item.value) !== -1
      })
      item.supplyModeOptions = options
    },
    designatedSupplierOnChange(selectRow, list, row) {
      row.designatedSupplier = selectRow.lifnr ?? ''
      row.designatedSupplierName = selectRow.name1Gp ?? ''
    },
    LocationCodeOnChange(selectRow, list, row) {
      console.log({selectRow})
      row.purInventoryAdd = selectRow.lgortD ?? ''
      row.purInventoryAddName = selectRow.zlgobe ?? ''
    },
    getList() {
      let paramArr = JSON.parse(this.$route.query.params)
      console.log(paramArr)
      let noVoList = paramArr.map(n => {
        const businessKey = n.businessKey
        return {
          reqNo: businessKey.substring(0, 7),
          reqItemNo: businessKey.substring(7, 10),
        }
      })
      let params = {
        noVoList,
        reqItemCriteria: this.listQuery
      }
      this.listParams = params
      doPost('peas-module-plan-biz', '/req/query-to-approve-req-list', params).then(res => {
        res.forEach(item => {
          if (!item.approveNum) {
            item.approveNum = item.submitQuantity
          }
          item.taskName = paramArr.find(item1 => (item.reqNo + item.reqItemNo) === item1.businessKey)?.taskName
          // this.getSupplyModeOptions(item)
        })
        this.tableData = res
        console.log({tableData: this.tableData})
        const ids = res.map(item => item.createBy).join(',')
        if (ids) {
          getUsers(ids).then(userRes => {
            if (typeof userRes == 'string') {
              this.userObj = {
                [res[0].createBy]: userRes
              }
            } else {
              this.userObj = userRes
            }
          })
        }
      })
    },
    verify(params) {
      if (params.approveFlag === 'N' && !params.comment) {
        this.$message.error('请输入审批意见')
        return false
      }
      let isVerify = true
      for (let i = 0; i < params.approvalItemVoList.length; i++) {
        let itemIsVerify = true
        let notVerifyArr = []
        let item = params.approvalItemVoList[i]
        let reqItemExVo = item.reqItemExVo
        let {taskName} = reqItemExVo
        if (!taskName?.includes('产品经理')) {
          continue
        }
        let isPrepaid = (reqItemExVo.prepaidFlag === '1')   // 是否预付物料
        if (!reqItemExVo.commissionBusiCode && reqItemExVo.commissionBusiCode !== 0 && reqItemExVo.commissionBusiCode !== '0') {
          console.log('请输入受托业务')
          isVerify = false
          itemIsVerify = false
          notVerifyArr.push('commissionBusiCode')
        }
        if (!reqItemExVo.approveNum) {
          console.log('请输入审核数量')
          isVerify = false
          itemIsVerify = false
          notVerifyArr.push('approveNum')
        }
        if (!reqItemExVo.planDod) {
          console.log('计划交货日期')
          isVerify = false
          itemIsVerify = false
          notVerifyArr.push('planDod')
        }
        if (!reqItemExVo.supplyMode) {
          console.log('请输入供货方式')
          isVerify = false
          itemIsVerify = false
          notVerifyArr.push('supplyMode')
        }
        if (params.approveFlag === 'Y' && !reqItemExVo.whseTurnoverRate && isPrepaid) {
          console.log('请输入预估提货后总仓周转率')
          isVerify = false
          itemIsVerify = false
          notVerifyArr.push('whseTurnoverRate')
        }
        if (params.approveFlag === 'Y' && !reqItemExVo.coTurnoverRate && isPrepaid) {
          console.log('请输入预估提货后全公司周转率')
          isVerify = false
          itemIsVerify = false
          notVerifyArr.push('coTurnoverRate')
        }
        if (reqItemExVo.commissionBusiCode == '1' && !reqItemExVo.designatedSupplier) {
          console.log('受托业务，请输入供应商')
          isVerify = false
          itemIsVerify = false
          notVerifyArr.push('designatedSupplier')
        }
        if (!itemIsVerify) {
          reqItemExVo.error = true
          reqItemExVo.notVerifyArr = notVerifyArr
        } else {
          delete reqItemExVo.error
          delete reqItemExVo.notVerifyArr
        }
      }
      return isVerify
    },
    /**
     * 同意 驳回
     * @param {*} val Y 同意  N 驳回
     */
    complete(val) {
      const {multipleSelection, tableData} = this
      if (multipleSelection.length === 0) {
        this.$alert(`请选择要${val == 'Y' ? '同意' : '驳回'}的数据`, "提示", {type: 'warning'})
        return false
      }
      let arr = JSON.parse(this.$route.query.params)
      let approvalItemVoList = this.multipleSelection.map(item => {
        let obj = {
          // procInsId: item.procInsId,	// 流程实例ID
          procInsId: arr.find(item1 => (item.reqNo + item.reqItemNo) === item1.businessKey).procInsId,	// 流程实例ID
          // taskId: item.taskId,	// 任务唯一标识
          taskId: arr.find(item1 => (item.reqNo + item.reqItemNo) === item1.businessKey).taskId,	// 任务唯一标识
          reqItemExVo: tableData.find(item1 => item.reqNo == item1.reqNo && item.reqItemNo == item1.reqItemNo)
        }
        obj.reqItemExVo.approveAmount = obj.reqItemExVo.reportPrice * obj.reqItemExVo.approveNum
        return obj
      })
      let params = {
        comment: this.obj.comment,	// 审批意见
        approveFlag: val, // 同意 驳回
        approvalItemVoList: approvalItemVoList,
      }
      if (!this.verify(params)) {
        this.$message.error('请输入必填项')
        return false
      }
      if (params.comment) {
        params.comment = (val == 'Y' ? '同意：' : '驳回：') + params.comment
      } else {
        params.comment = '同意'
      }
      doPost('peas-module-plan-biz', '/req/approval-modify', params).then(() => {
        notifySuccess('操作成功')
        this.listDelete()
      })
    },
    doClose() {
      let path = getPathByName('BpmTodo')
      // const obj = {path: '/bpm/task-management/todo'}
      const obj = {path}
      this.$tab.closeOpenPage(obj)
    },
  }
}
</script>

<style scoped lang="scss">
:deep .wraplabel {
  label {
    line-height: 16px !important;
    text-align: right !important;
  }
}

.app-container {
  .my-info-title-box {
    margin-bottom: 1rem;

    .color-block {
      float: left;
      width: 0.38rem;
      height: 1.3rem;
      background-color: rgb(48, 135, 180);
      margin-right: 0.5rem;
    }

    .my-info-title {
      display: contents;
      font-weight: 650;
      font-style: normal;
      font-size: 1rem;
      line-height: 1.3rem;
      color: #1600FF;
    }
  }

  .basic-info-body {
    margin-bottom: 2rem;
  }
}

</style>
<style>
.el-table .is-error .el-input__wrapper {
  box-shadow: 0 0 0 1px var(--el-color-danger) inset;
}

.el-table .errorTip {
  color: var(--el-color-danger);
  font-size: 12px;
  line-height: 1;
  position: absolute;
  bottom: 4px;
  left: 10px;
}
</style>
